<template>
  <div>
    <a-input-search
      v-model="selectedWarehouseNames"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch">
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel">
      
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item label="仓库编号">
                  <a-input placeholder="请输入仓库编号" v-model="queryParam.warehouseCode" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="仓库名称">
                  <a-input placeholder="请输入仓库名称" v-model="queryParam.warehouseName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <!-- <a-col :md="8" :sm="12">
                <a-form-item label="仓库类型">
                  <j-dict-select-tag 
                    placeholder="请选择仓库类型" 
                    v-model="queryParam.warehouseType" 
                    dictCode="warehouse_type" 
                    allowClear 
                    :style="{width: '100%'}"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="状态">
                  <j-dict-select-tag 
                    placeholder="请选择状态" 
                    v-model="queryParam.status" 
                    dictCode="warehouse_status" 
                    allowClear 
                    :style="{width: '100%'}"
                  />
                </a-form-item>
              </a-col> -->
              <a-col :md="8" :sm="12">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        
        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: multiple ? 'checkbox' : 'radio'}"
          :customRow="customRowClick"
          @change="handleTableChange">
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text === '0' ? 'green' : 'red'">
              {{ text === '0' ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template slot="warehouseTypeSlot" slot-scope="text">
            <j-dict-label :value="text" dictCode="warehouse_type"/>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JDictLabel from '@/components/dict/JDictLabel.vue'
  
  export default {
    name: 'JSelectWarehouseModal',
    components: {
      JDictSelectTag,
      JDictLabel
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请选择仓库'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      modalWidth: {
        type: Number,
        default: 1000
      },
      multiple: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '选择仓库'
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        selectedRowKeys: [],
        selectedWarehouseKeys: [], // 保存选择的仓库ID
        selectedWarehouseNames: '', // 保存选择的仓库名称
        selectedWarehouses: [], // 保存选择的仓库信息
        
        // 查询条件
        queryParam: {
          warehouseCode: '',
          warehouseName: '',
          warehouseType: '',
          status: ''
        },
        
        // 数据源
        dataSource: [],
        
        // 表格列
        columns: [
          {
            title: '仓库编号',
            dataIndex: 'warehouseCode',
            width: '20%',
            align: 'center'
          },
          {
            title: '仓库名称',
            dataIndex: 'warehouseName',
            width: '25%',
            align: 'center'
          },
          {
            title: '仓库类型',
            dataIndex: 'warehouseType',
            width: '20%',
            align: 'center',
            scopedSlots: { customRender: 'warehouseTypeSlot' }
          },
          {
            title: '库位数量',
            dataIndex: 'locationCount',
            width: '15%',
            align: 'center'
          },
          {
            title: '状态',
            dataIndex: 'status',
            width: '15%',
            align: 'center',
            scopedSlots: { customRender: 'statusSlot' }
          }
        ],
        
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        
        loading: false,
        url: {
          list: '/wms/warehouse/list',
          listAll: '/wms/warehouse/listAll',
          getWarehousesByIds: '/wms/warehouse/getWarehousesByIds'
        }
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val) {
            this.initSelectedWarehouse(val);
          } else {
            this.selectedWarehouseKeys = [];
            this.selectedWarehouseNames = '';
            this.selectedWarehouses = [];
            this.selectedRowKeys = [];
          }
        }
      }
    },
    methods: {
      // 自定义行点击事件
      customRowClick(record) {
        return {
          onClick: () => {
            this.handleRowClick(record);
          }
        };
      },
      
      // 初始化已选择的仓库信息
      initSelectedWarehouse(selectedIds) {
        if (!selectedIds) return;
        
        this.loading = true;
        let params = { ids: selectedIds };
        
        getAction(this.url.getWarehousesByIds, params).then(res => {
          if (res.success) {
            this.selectedWarehouses = res.result || [];
            this.selectedWarehouseKeys = this.selectedWarehouses.map(item => item.id);
            this.selectedWarehouseNames = this.selectedWarehouses.map(item => item.warehouseName).join(',');
            this.selectedRowKeys = this.selectedWarehouseKeys;
          } else {
            // 如果没有专用API，使用已有数据处理
            this.fallbackInitSelectedWarehouse(selectedIds);
          }
        }).catch(() => {
          // 如果API调用失败，使用已有数据处理
          this.fallbackInitSelectedWarehouse(selectedIds);
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 备用方法：当没有专用API时使用
      fallbackInitSelectedWarehouse(selectedIds) {
        const idsArray = selectedIds.split(',');
        // 加载所有仓库数据，然后筛选出已选择的
        getAction(this.url.listAll).then(res => {
          if (res.success) {
            const allWarehouses = res.result || [];
            this.selectedWarehouses = allWarehouses.filter(item => idsArray.includes(item.id));
            this.selectedWarehouseKeys = this.selectedWarehouses.map(item => item.id);
            this.selectedWarehouseNames = this.selectedWarehouses.map(item => item.warehouseName).join(',');
            this.selectedRowKeys = this.selectedWarehouseKeys;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 打开选择框
      handleSearch() {
        if (this.disabled) return;
        
        this.visible = true;
        this.loadData(1);
      },
      
      // 加载数据
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        
        const params = this.getQueryParams();
        this.loading = true;
        
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 获取查询参数
      getQueryParams() {
        const param = Object.assign({}, this.queryParam);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
      
      // 选择改变
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        
        if (!this.multiple) {
          this.selectedWarehouses = selectedRows;
        } else {
          // 保持已经选择的和当前页面选择的
          const selectedIds = selectedRows.map(row => row.id);
          this.selectedWarehouses = this.selectedWarehouses.filter(item => {
            return selectedIds.includes(item.id) || !this.dataSource.map(row => row.id).includes(item.id);
          });
          
          // 添加当前页面新选择的
          selectedRows.forEach(row => {
            const exist = this.selectedWarehouses.some(item => item.id === row.id);
            if (!exist) {
              this.selectedWarehouses.push(row);
            }
          });
        }
      },
      
      // 查询按钮
      searchQuery() {
        this.loadData(1);
      },
      
      // 重置按钮
      searchReset() {
        this.queryParam = {
          warehouseCode: '',
          warehouseName: '',
          warehouseType: '',
          status: ''
        };
        this.loadData(1);
      },
      
      // 表格分页、排序、筛选变化
      handleTableChange(pagination, filters, sorter) {
        this.ipagination.current = pagination.current;
        this.ipagination.pageSize = pagination.pageSize;
        this.loadData();
      },
      
      // 处理行点击事件
      handleRowClick(record) {
        // 获取当前行的key
        const rowKey = record.id;
        
        // 根据是否多选处理不同的逻辑
        if (!this.multiple) {
          // 单选模式：直接设置当前行为选中状态
          this.selectedRowKeys = [rowKey];
          this.selectedWarehouses = [record];
        } else {
          // 多选模式：切换选中状态
          const index = this.selectedRowKeys.indexOf(rowKey);
          if (index === -1) {
            // 如果未选中，则添加到选中列表
            this.selectedRowKeys.push(rowKey);
            
            // 检查记录是否已存在于selectedWarehouses中
            const exist = this.selectedWarehouses.some(item => item.id === record.id);
            if (!exist) {
              this.selectedWarehouses.push(record);
            }
          } else {
            // 如果已选中，则从选中列表移除
            this.selectedRowKeys.splice(index, 1);
            
            // 从selectedWarehouses中移除
            const warehouseIndex = this.selectedWarehouses.findIndex(item => item.id === record.id);
            if (warehouseIndex !== -1) {
              this.selectedWarehouses.splice(warehouseIndex, 1);
            }
          }
        }
      },
      
      // 确定按钮
      handleOk() {
        this.selectedWarehouseKeys = this.selectedWarehouses.map(item => item.id);
        this.selectedWarehouseNames = this.selectedWarehouses.map(item => item.warehouseName).join(',');
        
        this.$emit('input', this.selectedWarehouseKeys.join(','));
        this.$emit('change', this.selectedWarehouseKeys.join(','), this.selectedWarehouses);
        
        this.handleCancel();
      },
      
      // 取消按钮
      handleCancel() {
        this.visible = false;
      }
    }
  }
</script>

<style scoped>
  .query-area {
    margin-bottom: 16px;
  }
  
  /* 统一下拉框和输入框样式 */
  :deep(.ant-select) {
    width: 100% !important;
  }
  
  :deep(.ant-select-selection) {
    width: 100% !important;
  }
  
  /* 添加鼠标悬停样式，提升用户体验 */
  :deep(.ant-table-tbody > tr) {
    cursor: pointer;
  }
  
  :deep(.ant-table-tbody > tr:hover) {
    background-color: #e6f7ff;
  }
</style> 